package com.levi.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.levi.mapper.SysRoleMenuMapper;
import com.levi.mapper.SysUserMapper;
import com.levi.mapper.SysUserRoleMapper;
import com.levi.pojo.SysRoleMenu;
import com.levi.pojo.SysUser;
import com.levi.pojo.SysUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    SysUserMapper userMapper;

    @Resource
    SysUserRoleMapper userRoleMapper;

    @Resource
    SysRoleMenuMapper roleMenuMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("用户名: " + username);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        //根据用户名查找用户是否存在
        SysUser sysUser = userMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            throw new UsernameNotFoundException(username + " 用户未找到");
        }
        //获取用户角色
        SysUserRole userRole = userRoleMapper.selectById(sysUser.getId());
        List<String> menuCodeList = new ArrayList<String>();

        if (userRole != null) {
            QueryWrapper<SysRoleMenu> sysRoleMenuQueryWrapper = new QueryWrapper<>();
            sysRoleMenuQueryWrapper.eq("role_id", userRole.getRoleId());
            List<SysRoleMenu> roleMenuList = roleMenuMapper.selectList(sysRoleMenuQueryWrapper);
            menuCodeList = roleMenuList.stream().map(SysRoleMenu::getMenuCode).collect(Collectors.toList());
        }else {
            menuCodeList.add("none_menu");
        }

        //最后返回spring security需要的user
        return new User(username,
                sysUser.getPassword(),
                sysUser.getEnabled(),
                true,
                true,
                sysUser.getAccountNonLocked(),
                AuthorityUtils.createAuthorityList(menuCodeList.toArray(new String[menuCodeList.size()])));
    }
}
